package com.antis.olsl.magic.report;

import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.antis.olsl.arouterlib.MagicRoutePath;
import com.antis.olsl.base.BaseActivity;
import com.antis.olsl.library.dialog.ChooseDateDialog;
import com.antis.olsl.library.dialog.ChooseSalesroomsOrWarehouseDialog;
import com.antis.olsl.library.response.GetSalesroomOrWarehouseListRes;
import com.antis.olsl.library.response.SalesroomOrWarehouseInfo;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.library.widget.ChooseSalesroomOrWarehouseView;
import com.antis.olsl.magic.adapter.MagicIndicatorAdapter;
import com.antis.olsl.magic.databinding.ActivitySalesReportBinding;
import com.antis.olsl.magic.report.annual.AnnualFragment;
import com.antis.olsl.magic.report.daily.DailyFragment;
import com.antis.olsl.magic.report.month.MonthlyFragment;
import com.antis.olsl.magic.report.quarterly.QuarterlyFragment;
import com.antis.olsl.magic.report.weekly.WeeklyFragment;
import com.trello.rxlifecycle2.LifecycleTransformer;

import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import timber.log.Timber;

/**
 * 销售报表
 *
 * @author hhh
 */
@Route(path = MagicRoutePath.ACTIVITY_SALES_REPORT)
public class SalesReportActivity extends BaseActivity<ActivitySalesReportBinding> implements SalesReportContract.View, ChooseSalesroomOrWarehouseView.ChooseSalesroomOrWarehouseListener,
        ChooseSalesroomsOrWarehouseDialog.ChooseSalesroomOrWarehouseListener, ChooseDateDialog.ChooseDateListener {

    private String[] mDataList = {"日报", "周报", "月报", "季报", "年报"};
    private List<Fragment> mFragments;
    private FragmentPagerAdapter mAdapter;

    private boolean chooseAllSalesroom = true;
    private ArrayList<SalesroomOrWarehouseInfo> salesroomInfos = new ArrayList<>();
    private ArrayList<SalesroomOrWarehouseInfo> selectedSalesroomInfos = new ArrayList<>();
    private ChooseSalesroomsOrWarehouseDialog chooseSalesroomsOrWarehouseDialog;

    private DailyFragment mDailyFragment;
    private WeeklyFragment mWeeklyFragment;
    private MonthlyFragment monthlyFragment;
    private QuarterlyFragment mQuarterlyFragment;
    private AnnualFragment mAnnualFragment;

    private SalesReportPresenter mPresenter;
    private ChooseDateDialog chooseDateDialog;
    private SimpleDateFormat textYearFormat = new SimpleDateFormat("yyyy年", Locale.getDefault());
    private SimpleDateFormat textMonthFormat = new SimpleDateFormat("yyyy年MM月", Locale.getDefault());
    private SimpleDateFormat textDateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
    private SimpleDateFormat strDateFormat = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());

    private Date startYear;
    private Date startQuarter;
    private Date startMonth;
    private Date startWeek;
    private Date startDate;

    private int mPosition = 0;
    private int mType = 0;
    private int mWeekPosition;
    private int mQuarterPosition;

    private String strStartDate;
    private String strTextDate;
    private String salesRoomIds;

    private int intWeekYear;
    private int intWeek;

    private int intMonthYear;
    private int intMonth;

    private int intQuarterYear;
    private int intQuarter;

    private int intYear;

    private void initDate() {
        Calendar calendar = Calendar.getInstance();
        //初始进来查询昨天的数据
        calendar.add(Calendar.DATE, -1);
        startDate = calendar.getTime();

        Calendar calendarMonth = Calendar.getInstance();
        startYear = calendarMonth.getTime();
        startQuarter = calendarMonth.getTime();
        startMonth = calendarMonth.getTime();
        startWeek = calendarMonth.getTime();

        intWeekYear = calendarMonth.get(Calendar.YEAR);
        intWeek = calendarMonth.get(Calendar.WEEK_OF_YEAR);

        intMonthYear = calendarMonth.get(Calendar.YEAR);
        intMonth = calendarMonth.get(Calendar.MONTH) + 1;

        intQuarterYear = calendarMonth.get(Calendar.YEAR);
        intQuarter = getYearQuarterIndex(startQuarter);

        intYear = calendarMonth.get(Calendar.YEAR);

        initDateText();
    }

    private void initFragments() {
        mDailyFragment = DailyFragment.newInstance(salesRoomIds, strStartDate, strTextDate);
        mWeeklyFragment = WeeklyFragment.newInstance(salesRoomIds, intWeekYear, intWeek);
        monthlyFragment = MonthlyFragment.newInstance(salesRoomIds, intMonthYear, intMonth);
        mQuarterlyFragment = QuarterlyFragment.newInstance(salesRoomIds, intQuarterYear, intQuarter);
        mAnnualFragment = AnnualFragment.newInstance(salesRoomIds, intYear);

        mFragments = new ArrayList<>(5);
        mFragments.add(mDailyFragment);
        mFragments.add(mWeeklyFragment);
        mFragments.add(monthlyFragment);
        mFragments.add(mQuarterlyFragment);
        mFragments.add(mAnnualFragment);

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager(), 0) {
            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return mDataList[position];
            }

            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }
        };
        viewBinding.viewPager.setAdapter(mAdapter);

        viewBinding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                Timber.tag("hhh").e("position= " + position);
                mPosition = position;
                setLabel(position);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }

    private void initMagicIndicator() {
        final List<String> titleList = new ArrayList<>(5);
        titleList.add("日报");
        titleList.add("周报");
        titleList.add("月报");
        titleList.add("季报");
        titleList.add("年报");
        CommonNavigator commonNavigator = new CommonNavigator(this);
        MagicIndicatorAdapter magicIndicatorAdapter = new MagicIndicatorAdapter(this, viewBinding.viewPager);
        magicIndicatorAdapter.setTitleList(titleList);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(magicIndicatorAdapter);
        viewBinding.magicIndicator.setNavigator(commonNavigator);

        ViewPagerHelper.bind(viewBinding.magicIndicator, viewBinding.viewPager);
    }

    private void initDateText() {
        strStartDate = strDateFormat.format(startDate);
        strTextDate = textDateFormat.format(startDate);
        viewBinding.tvDate.setText(strTextDate);
    }

    private void setLabel(int position) {
        switch (position) {
            case 0: {
                setDateText();
            }
            break;
            case 1: {
                if (mWeekPosition == 0) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startWeek);
                    int year = calendar.get(Calendar.YEAR);
                    int week = calendar.get(Calendar.WEEK_OF_YEAR);
                    setWeekText(year, week);
                } else {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startWeek);
                    int year = calendar.get(Calendar.YEAR);
                    setWeekText(year, mWeekPosition);
                }
            }
            break;
            case 2: {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startMonth);
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1;
                setMonthText(year, month);
            }
            break;
            case 3: {
                if (mQuarterPosition == 0) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startQuarter);
                    int year = calendar.get(Calendar.YEAR);
                    int quarter = getYearQuarterIndex(startQuarter);
                    mQuarterPosition = quarter;
                    setQuarterText(year, quarter);
                } else {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(startQuarter);
                    int year = calendar.get(Calendar.YEAR);
                    setQuarterText(year, mQuarterPosition);
                }
            }
            break;
            case 4: {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startMonth);
                int year = calendar.get(Calendar.YEAR);
                setYearText(year);
            }
            break;
            default:
                break;
        }
    }

    /**
     * 当前属于本年第几个季度
     *
     * @return int
     */
    public int getYearQuarterIndex(Date date) {
        int month = getYearMonthIndex(date);
        if (month <= 3) {
            return 1;
        } else if (month <= 6) {
            return 2;
        } else if (month <= 9) {
            return 3;
        } else {
            return 4;
        }
    }

    /**
     * 属于本年第几月
     *
     * @return
     */
    public int getYearMonthIndex(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    @Override
    protected ActivitySalesReportBinding getViewBinding() {
        return ActivitySalesReportBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initPresenter() {
        super.initPresenter();
        mPresenter = new SalesReportPresenter();
        mPresenter.takeView(this);
    }

    @Override
    protected void initViews() {
        initDate();
        initFragments();
        initMagicIndicator();

        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroomOrWarehouseInfos(null);
        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setChooseSalesroomOrWarehouseListener(this);

        viewBinding.rlChooseDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Date selectedDate = startDate;
                switch (mPosition) {
                    case 0:
                        selectedDate = startDate;
                        break;
                    case 1:
                        selectedDate = startWeek;
                        break;
                    case 2:
                        selectedDate = startMonth;
                        break;
                    case 4:
                        selectedDate = startYear;
                        break;
                    default:
                        break;
                }
                chooseDateDialog = new ChooseDateDialog(SalesReportActivity.this, "选择时间", selectedDate, SalesReportActivity.this, "startDate", mWeekPosition, mQuarterPosition, mType);
                setTimeShow(mPosition);
            }
        });
    }

    @Override
    protected void initData() throws IllegalAccessException {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) {
            mPresenter.unSubscribe();
        }
    }

    @Override
    public void getSalesroomInfoListSuccess(GetSalesroomOrWarehouseListRes resp) {
        salesroomInfos.clear();
        salesroomInfos.addAll(resp.getContent());
        Timber.tag("hhh").e("GetSalesroomOrWarehouseListRes resp= " + resp.getContent().size());

        chooseSalesroomsOrWarehouseDialog = new ChooseSalesroomsOrWarehouseDialog(this, 0, salesroomInfos, SalesReportActivity.this);
    }

    @Override
    public void getSalesroomInfoListFailure(String msg) {
        Timber.tag("hhh").e("getSalesroomInfoListFailure");
        if (TextUtils.isEmpty(msg)) {
            msg = "请求失败,请稍后重试";
        }
        ToastUtil.showToast(this, msg);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    @Override
    public void clickChooseListener() {
        if (salesroomInfos == null || salesroomInfos.size() == 0) {
            getSalesroomOrWareList();
        } else {
            chooseSalesroomsOrWarehouseDialog = new ChooseSalesroomsOrWarehouseDialog(this, 0, salesroomInfos, SalesReportActivity.this);
        }
    }

    /**
     * 获取门店或仓库列表
     */
    private void getSalesroomOrWareList() {
        HashMap<String, Object> map = new HashMap<>();
        mPresenter.getSalesroomInfoList(map);
    }

    @Override
    public void clickPhone(String phone) {
        // callPhone(phone);
    }

    @Override
    public void onChooseSalesroomOrWarehouseListener(boolean isChooseAll, ArrayList<SalesroomOrWarehouseInfo> choosedFiledInfos, ArrayList<SalesroomOrWarehouseInfo> sourceInofs, int selectedIndex) {
        chooseAllSalesroom = isChooseAll;
        selectedSalesroomInfos = choosedFiledInfos;
        salesroomInfos = sourceInofs;
        if (selectedIndex == -1) {
            salesRoomIds = "";
            viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroomOrWarehouseInfos(null);
        } else {
            salesRoomIds = filterIds();
        }

        Timber.tag("hhh").e("mPosition= " + mPosition);
        if (mPosition == 0) {
            if (null != mDailyFragment) {
                mDailyFragment.loadData(salesRoomIds, strStartDate, strTextDate);
            }
        } else if (mPosition == 1) {
            if (null != mWeeklyFragment) {
                mWeeklyFragment.loadData(salesRoomIds, intWeekYear, intWeek);
            }
        } else if (mPosition == 2) {
            if (null != monthlyFragment) {
                monthlyFragment.loadData(salesRoomIds, intMonthYear, intMonth + 1);
            }
        } else if (mPosition == 3) {
            if (null != mQuarterlyFragment) {
                mQuarterlyFragment.loadData(salesRoomIds, intQuarterYear, intQuarter);
            }
        } else if (mPosition == 4) {
            if (null != mAnnualFragment) {
                mAnnualFragment.loadData(salesRoomIds, intYear);
            }
        }
    }

    public String filterIds() {
        ArrayList<SalesroomOrWarehouseInfo> infos = (chooseAllSalesroom ? salesroomInfos : selectedSalesroomInfos);
        String name = "";
        String ids = "";
        for (int i = 0; i < infos.size(); i++) {
            ids += TextUtils.isEmpty(ids) ? infos.get(i).getId() : "," + infos.get(i).getId();
            if (chooseAllSalesroom) {
                continue;
            }
            name += TextUtils.isEmpty(name) ? infos.get(i).getName() : "," + infos.get(i).getName();
        }
        boolean chooseALL = false;
        if (chooseAllSalesroom) {
            name = "全部门店";
            chooseALL = true;
        }
        viewBinding.layoutChooseSalesroomOrWarehouse.chooseSalesroomOrWarehouseView.setSalesroomOrWarehouseInfos(infos);
        return ids;
    }

    private void setTimeShow(int position) {
        switch (position) {
            case 0:
                chooseDateDialog.setQuarterHint();
                chooseDateDialog.setMonthShow();
                chooseDateDialog.setWeekHint();
                chooseDateDialog.setDayShow();
                break;
            case 1:
                chooseDateDialog.setQuarterHint();
                chooseDateDialog.setDayHint();
                chooseDateDialog.setMonthHint();
                chooseDateDialog.setWeekShow();
                break;
            case 2:
                chooseDateDialog.setQuarterHint();
                chooseDateDialog.setDayHint();
                chooseDateDialog.setMonthShow();
                chooseDateDialog.setWeekHint();
                break;
            case 3:
                chooseDateDialog.setQuarterShow();
                chooseDateDialog.setDayHint();
                chooseDateDialog.setMonthHint();
                chooseDateDialog.setWeekHint();
                break;
            case 4:
                chooseDateDialog.setQuarterHint();
                chooseDateDialog.setDayHint();
                chooseDateDialog.setMonthHint();
                chooseDateDialog.setWeekHint();
                break;
            default:
                break;
        }
    }

    @Override
    public void getDateListener(String tag, int year, int quarter, int month, int week, int day) {
        chooseDateDialog.dismiss();
        Date tmpDate = new Date();
        switch (mPosition) {
            case 0:
                setData(tmpDate, year, month, day);
                break;
            case 1:
                setWeek(tmpDate, year, week);
                break;
            case 2:
                setMonth(tmpDate, year, month);
                break;
            case 3:
                setQuarter(tmpDate, year, quarter);
                break;
            case 4:
                setYear(tmpDate, year);
                break;
            default:
                break;
        }
    }

    private void setData(Date tmpDate, int year, int month, int day) {
        try {
            tmpDate = textDateFormat.parse(year + "年" + month + "月" + day + "日");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        startDate = tmpDate;
        setDateText();
    }

    private void setWeek(Date tmpDate, int year, int week) {
        startWeek = tmpDate;
        mWeekPosition = week;
        setWeekText(year, week);
    }

    private void setMonth(Date tmpDate, int year, int month) {
        try {
            tmpDate = textMonthFormat.parse(year + "年" + month + "月");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        startMonth = tmpDate;
        setMonthText(year, month);
    }

    private void setQuarter(Date tmpDate, int year, int quarter) {
        startWeek = tmpDate;
        mQuarterPosition = quarter;
        setQuarterText(year, quarter);
    }

    private void setYear(Date tmpDate, int year) {
        try {
            tmpDate = textYearFormat.parse(year + "年");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        startYear = tmpDate;
        setYearText(year);
    }

    private void setDateText() {
        strStartDate = strDateFormat.format(startDate);
        strTextDate = textDateFormat.format(startDate);
        viewBinding.tvDate.setText(strTextDate);
        if (mPosition == 0) {
            Timber.tag("hhh").e("mPosition= " + mPosition);
            if (null != mDailyFragment) {
                mDailyFragment.loadData(salesRoomIds, strStartDate, strTextDate);
            }
        }
    }

    private void setWeekText(int year, int week) {
        intWeekYear = year;
        intWeek = week;
        viewBinding.tvDate.setText(year + "年" + week + "周");

        if (mPosition == 1) {
            Timber.tag("hhh").e("mPosition= " + mPosition);
            if (null != mWeeklyFragment) {
                mWeeklyFragment.loadData(salesRoomIds, intWeekYear, intWeek);
            }
        }
    }

    private void setMonthText(int year, int month) {
        intMonthYear = year;
        intMonth = month;
        // tvDate.setText(year + "年" + month + "月");
        viewBinding.tvDate.setText(textMonthFormat.format(startMonth));

        if (mPosition == 2) {
            if (null != monthlyFragment) {
                monthlyFragment.loadData(salesRoomIds, intMonthYear, intMonth);
            }
        }
    }

    private void setQuarterText(int year, int quarter) {
        intQuarterYear = year;
        intQuarter = quarter;
        viewBinding.tvDate.setText(year + "年" + quarter + "季度");

        if (mPosition == 2) {
            if (null != monthlyFragment) {
                mQuarterlyFragment.loadData(salesRoomIds, intQuarterYear, intQuarter);
            }
        }
    }

    private void setYearText(int year) {
        this.intYear = year;
        viewBinding.tvDate.setText(textYearFormat.format(startYear));

        if (mPosition == 4) {
            if (null != mAnnualFragment) {
                mAnnualFragment.loadData(salesRoomIds, intYear);
            }
        }
    }
}
